package com.hskn.hss.module.tlcar.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hskn.hss.core.annotation.DataScope;
import com.hskn.hss.core.domain.BaseEntity;
import com.hskn.hss.core.utils.LoginUtils;
import com.hskn.hss.entity.AjaxResult;
import com.hskn.hss.entity.TreeEntity;
import com.hskn.hss.exception.ExcelReaderDataException;
import com.hskn.hss.exception.HssException;
import com.hskn.hss.module.depart.entity.SysDepart;
import com.hskn.hss.module.depart.mapper.SysDepartMapper;
import com.hskn.hss.module.depart.service.ISysDepartService;
import com.hskn.hss.module.grid.entity.Grid;
import com.hskn.hss.module.grid.mapper.GridMapper;
import com.hskn.hss.module.gridbind.entity.GridBind;
import com.hskn.hss.module.gridbind.mapper.GridBindMapper;
import com.hskn.hss.module.tlcar.entity.TICarVo;
import com.hskn.hss.module.tlcar.entity.TlCar;
import com.hskn.hss.module.tlcar.mapper.TlCarMapper;
import com.hskn.hss.module.tlcar.service.ITlCarService;
import com.hskn.hss.module.tlcar.to.TlCarTo;
import com.hskn.hss.module.tlcar.vo.TlcarPageVo;
import com.hskn.hss.module.tlcarmanufacturer.entity.TlCarManufacturer;
import com.hskn.hss.module.tlcarmanufacturer.mapper.TlCarManufacturerMapper;
import com.hskn.hss.module.tlcarmodel.entity.TlCarModel;
import com.hskn.hss.module.tlcarmodel.mapper.TlCarModelMapper;
import com.hskn.hss.module.tlcarmodel.service.ITlCarModelService;
import com.hskn.hss.module.tlcartype.entity.TlCarType;
import com.hskn.hss.module.tlcartype.mapper.TlCarTypeMapper;
import com.hskn.hss.module.tlchannel.entity.TlChannel;
import com.hskn.hss.module.tlchannel.mapper.TlChannelMapper;
import com.hskn.hss.module.tlequip.entity.TlEquip;
import com.hskn.hss.module.tlequip.service.impl.TlEquipServiceImpl;
import com.hskn.hss.module.tlequipbind.mapper.TlEquipBindMapper;
import com.hskn.hss.module.tloperationitem.entity.TlOperationItem;
import com.hskn.hss.module.tloperationitem.mapper.TlOperationItemMapper;
import com.hskn.hss.module.tlopetation.entity.TlOperation;
import com.hskn.hss.module.tlopetation.mapper.TlOperationMapper;
import com.hskn.hss.module.tlthreshold.entity.TlThreshold;
import com.hskn.hss.module.tlthreshold.mapper.TlThresholdMapper;
import com.hskn.hss.module.user.entity.User;
import com.hskn.hss.module.user.mapper.UserMapper;
import com.hskn.hss.module.user.service.IUserService;
import com.hskn.hss.module.userdepart.entity.SysUserDepart;
import com.hskn.hss.module.userdepart.mapper.SysUserDepartMapper;
import com.hskn.hss.utils.AttributeUtils;
import com.hskn.hss.utils.GroupingByUtils;
import com.hskn.hss.utils.StringUtils;
import com.hskn.hss.utils.TreeUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author hskn
 * @since 2021-05-17
 */
@Service
public class TlCarServiceImpl extends ServiceImpl<TlCarMapper, TlCar> implements ITlCarService {

    @Resource
    TlCarMapper tlCarMapper;
    @Resource
    SysUserDepartMapper sysUserDepartMapper;
    @Resource
    SysDepartMapper sysDepartMapper;
    @Autowired
    IUserService userService;
    @Autowired
    ITlCarModelService tlCarModelService;
    @Resource
    TlThresholdMapper tlThresholdMapper;
    @Resource
    TlCarModelMapper tlCarModelMapper;
    @Resource
    TlCarTypeMapper tlCarTypeMapper;
    @Resource
    TlEquipBindMapper tlEquipBindMapper;
    @Resource
    TlChannelMapper tlChannelMapper;
    @Resource
    TlCarManufacturerMapper carManufacturerMapper;
    @Resource
    private SysDepartMapper departMapper;
    @Resource
    TlOperationMapper tlOperationMapper;
    @Resource
    TlOperationItemMapper tlOperationItemMapper;
    @Resource
    GridBindMapper gridBindMapper;
    @Resource
    GridMapper gridMapper;
    @Resource
    TlEquipServiceImpl tlEquipService;
    @Resource
    UserMapper userMapper;
    @Resource
    ISysDepartService departService;


    @Override
    @Transactional//添加事务
    public AjaxResult insert(TlCar tlCar) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        QueryWrapper<SysUserDepart> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserDepart::getUserid, uid);
        String deptid = sysUserDepartMapper.selectOne(queryWrapper).getDepid();

        tlCar.setCreateby(uid);
        tlCar.setCreatetime(new Date());
        tlCar.setDeptid(deptid);
        if (tlCar.getStatus() == null || tlCar.getStatus().isEmpty()) {
            tlCar.setStatus("1");
        }
        tlCarMapper.insert(tlCar);

        Map map = new HashMap();
        map.put("thresholdtype", "car");
        List<TlThreshold> tlThresholdList = tlThresholdMapper.selectByMap(map);
        for (TlThreshold t : tlThresholdList) {
            t.setThresholdtype("item");
            t.setItemid(tlCar.getId());
            t.setId(StringUtils.uuid());
            tlThresholdMapper.insert(t);
        }
        return AjaxResult.success("操作成功");
    }


    @Override
    public AjaxResult update(JSONObject params) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        TlCar tlCar = params.getObject("data", TlCar.class);
        tlCar.setUpdateby(uid);
        tlCar.setUpdatetime(new Date());
        tlCarMapper.updateById(tlCar);
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult updatebyids(TlCar tlCar) throws HssException {

        String uid = LoginUtils.getUser().getUid();
        String ids = tlCar.getIds();
        String[] idArray = ids.split(",");
        tlCar.setUpdateby(uid);
        tlCar.setUpdatetime(new Date());

        UpdateWrapper<TlCar> tlCarUpdateWrapper = new UpdateWrapper<>();
        tlCarUpdateWrapper.lambda().in(TlCar::getId, idArray);

        tlCarMapper.update(tlCar, tlCarUpdateWrapper);
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult deletebyid(JSONObject params) throws HssException {
        String id = params.getString("id");
        tlCarMapper.deleteById(id);
        return AjaxResult.success("操作成功");
    }

    @Override
    public AjaxResult deletebatchbyid(TlCar tlCar) throws HssException {
        String ids = tlCar.getIds();
        String[] idArray = ids.split(",");
        tlCarMapper.deleteBatchIds(Arrays.asList(idArray));
        return AjaxResult.success("操作成功");
    }

    @Override
    public TlCar getDetail(JSONObject params) throws HssException {
        String id = params.getString("id");
        Long page = StringUtils.isEmpty(params.getLong("page")) ? 1 : params.getLong("page");
        Long size = StringUtils.isEmpty(params.getLong("size")) ? 10 : params.getLong("size");
        Map<String, Object> map = new HashMap();
        map.put("id", id);
        Page<TlCar> listPage = new Page<>(page, size, true);
        IPage<TlCar> iPage = tlCarMapper.listTlCar(listPage, map);
        TlCar tlCar = iPage.getRecords().get(0);

        String equipid = tlCar.getEquipid();
        if (!StringUtils.isEmpty(equipid)) {
            QueryWrapper<TlChannel> tlChannelQueryWrapper = new QueryWrapper<>();
            tlChannelQueryWrapper.lambda().eq(TlChannel::getEquipid, equipid);
            tlChannelQueryWrapper.lambda().orderByAsc(TlChannel::getChannelname);
            List details = tlChannelMapper.selectList(tlChannelQueryWrapper);
            tlCar.setChannels(details);
        }

        QueryWrapper<TlCarModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlCarModel::getId, tlCar.getCarmodelid());
        TlCarModel tlCarModel = tlCarModelMapper.selectOne(queryWrapper);
        QueryWrapper<TlCarManufacturer> carManufacturerQueryWrapper = new QueryWrapper<>();
        carManufacturerQueryWrapper.eq("id", tlCarModel.getManufacturer());
        TlCarManufacturer carManufacturer = carManufacturerMapper.selectOne(carManufacturerQueryWrapper);
        if (null != carManufacturer) {
            tlCarModel.setManufacturername(carManufacturer.getDicname());
        }
        tlCar.setDetails(tlCarModel);
        return tlCar;
    }

    @Override
    public List getSelectList() {
        List resultList = tlCarMapper.getSelectList();
        return resultList;
    }

    @Override
    @DataScope(deptAlias = "cardeptid", userAlias = "driverid, createby, updateby, bindaccount")
    public TlcarPageVo getList(BaseEntity entity, TlCarTo tlCarTo) throws HssException {

        QueryWrapper<GridBind> gridBindQueryWrapper = new QueryWrapper<>();
        List<GridBind> gridBindList = gridBindMapper.selectList(gridBindQueryWrapper);
        Map<String, List<GridBind>> gridBindCollect = gridBindList.stream().collect(Collectors.groupingBy(GridBind::getItemId));

        QueryWrapper<TlCar> tlCarQueryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotEmpty(tlCarTo.getCarCategory())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getCarcategory, tlCarTo.getCarCategory());
        }
        if (StringUtils.isNotEmpty(tlCarTo.getCarDeptId())) {
            List<String> depids = departService.getChildIdsByIId(tlCarTo.getCarDeptId());
            tlCarQueryWrapper.lambda().in(TlCar::getCardeptid, depids);
        }
        if (StringUtils.isNotEmpty(tlCarTo.getCarTypeId())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getCartypeid, tlCarTo.getCarTypeId());
        }
        if (StringUtils.isNotEmpty(tlCarTo.getCarAttribution())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getCarattribution, tlCarTo.getCarAttribution());
        }
        if (StringUtils.isNotEmpty(tlCarTo.getCarCategory())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getCarcategory, tlCarTo.getCarCategory());
        }
        if (StringUtils.isNotEmpty(tlCarTo.getStatus())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getStatus, tlCarTo.getStatus());
        }
        if (StringUtils.isNotEmpty(tlCarTo.getCarCategoryItem())) {
            tlCarQueryWrapper.lambda().eq(TlCar::getCarcategoryitem, tlCarTo.getCarCategoryItem());
        }
        if (StringUtils.isNotEmpty(tlCarTo.getCarNumber())) {
            tlCarQueryWrapper.lambda().in(TlCar::getCarnumber, tlCarTo.getCarNumber().split(","));
        }

        if (entity.getParams().containsKey("dataScope")&&StringUtils.isNotEmpty(entity.getParams().get("dataScope"))) {
            tlCarQueryWrapper.lambda().apply(entity.getParams().get("dataScope").toString());
        }
        List<TlCar> tlCarList = tlCarMapper.selectList(tlCarQueryWrapper);

        List<User> tlEmployeeList = userMapper.selectList(new QueryWrapper<>());
        Map<String,User> userMap = tlEmployeeList.stream().collect(Collectors.groupingBy(User ::getUid,Collectors.collectingAndThen(toList(), values -> values.get(0))));

        List<SysDepart> sysDepartList = departMapper.selectList(new QueryWrapper<>());
        Map<String, SysDepart> sysDepartMap = sysDepartList.stream().collect(Collectors.groupingBy(SysDepart::getId, Collectors.collectingAndThen(toList(), values -> values.get(0))));

        List<TlOperation> tlOperationList = tlOperationMapper.selectList(new QueryWrapper<>());
        Map<String, TlOperation> tlOperationMap = tlOperationList.stream().collect(Collectors.groupingBy(TlOperation::getId, Collectors.collectingAndThen(toList(), values -> values.get(0))));

        List<TlCarType> tlCarTypeList = tlCarTypeMapper.selectList(new QueryWrapper<>());
        Map<String, TlCarType> tlCarTypeMap = tlCarTypeList.stream().collect(Collectors.groupingBy(TlCarType::getId, Collectors.collectingAndThen(toList(), values -> values.get(0))));

        List<TlCarModel> tlCarModelList = tlCarModelMapper.selectList(new QueryWrapper<>());
        Map<String, TlCarModel> tlCarModelMap = tlCarModelList.stream().collect(Collectors.groupingBy(TlCarModel::getId, Collectors.collectingAndThen(toList(), values -> values.get(0))));

        List<Grid> gridList = gridMapper.selectList(new QueryWrapper<>());
        Map<String, Grid> gridMap = gridList.stream().collect(Collectors.groupingBy(Grid::getGridId, Collectors.collectingAndThen(Collectors.toList(), grids -> grids.get(0))));
        List<String> gridIdList = new ArrayList<>();
        for (TlCar tlCar : tlCarList) {
            SysDepart sysDepart = sysDepartMap.get(tlCar.getCardeptid());
            if (null != sysDepart) {
                tlCar.setCardeptname(sysDepart.getDepartName());
            }
            TlOperation tlOperation = tlOperationMap.get(tlCar.getCarcategory());
            if (null != tlOperation) {
                tlCar.setCarcategoryname(tlOperation.getOperationtype());
            }
            TlCarType tlCarType = tlCarTypeMap.get(tlCar.getCartypeid());
            if (null != tlCarType) {
                tlCar.setCarTypeName(tlCarType.getTypename());
            }
            TlCarModel tlCarModel = tlCarModelMap.get(tlCar.getCarmodelid());
            if (null != tlCarModel) {
                tlCar.setCarmodelname(tlCarModel.getCarmodel());
                tlCar.setDrivemodel(tlCarModel.getDrivemodel());
            }
            User user = userMap.get(tlCar.getBindaccount());
            if(null != user){
                tlCar.setBindaccountname(user.getName());
            }
            Map param = new HashMap();
            param.put("itemid", tlCar.getId());
            tlCar.setBinds(tlEquipBindMapper.selectByMap(param));
            List<GridBind> gridBindList1 = gridBindCollect.get(tlCar.getId());
            if (null != gridBindList1) {
                for (GridBind gridBind : gridBindList1) {
                    Grid grid = gridMap.get(gridBind.getGridId());
                    if (null != grid) {
                        gridBind.setGridName(grid.getName());
                        tlCar.getGridBindList().add(gridBind);
                        gridIdList.add(grid.getGridId());
                    }
                }
            }
        }
        if (StringUtils.isNotEmpty(tlCarTo.getBindingStatus()) && tlCarTo.getBindingStatus() == 2) {
            List<TlCar> tlCarListByBindId = tlCarList.stream().filter(tlCar -> (!tlCar.getGridBindList().isEmpty()) && (gridIdList.contains(tlCarTo.getGridId()))).collect(Collectors.toList());
            return page(tlCarTo, tlCarListByBindId);
        } else if (StringUtils.isNotEmpty(tlCarTo.getBindingStatus()) && tlCarTo.getBindingStatus() == 1) {
            List<TlCar> tlCarListByBindId = tlCarList.stream().filter(tlCar -> (tlCar.getGridBindList().isEmpty())).collect(Collectors.toList());
            return page(tlCarTo, tlCarListByBindId);
        } else {
            if (StringUtils.isNotEmpty(tlCarTo.getDriveModel())) {
                List<TlCar> tlCarListByModel = tlCarList.stream().filter(tlCar -> null != tlCar.getDrivemodel() && tlCar.getDrivemodel().equals(tlCarTo.getDriveModel())).collect(toList());
                return page(tlCarTo, tlCarListByModel);
            }
            return page(tlCarTo, tlCarList);
        }
    }

    private TlcarPageVo page(TlCarTo tlCarTo, List list) {
        // 分页
        Long page = StringUtils.isEmpty(tlCarTo.getPage()) ? 1 : tlCarTo.getPage();
        Long size = StringUtils.isEmpty(tlCarTo.getSize()) ? 10 : tlCarTo.getSize();
        TlcarPageVo tlcarPageVo = new TlcarPageVo();

        tlcarPageVo.setTotal((long) list.size());
        tlcarPageVo.setCurrent(page);
        tlcarPageVo.setSize(size);
        BigDecimal pageSizeB = new BigDecimal(size);
        BigDecimal sizeB = new BigDecimal(list.size());
        tlcarPageVo.setPages(Long.valueOf(sizeB.divide(pageSizeB, BigDecimal.ROUND_CEILING).toString()));

        tlcarPageVo.setList(new ArrayList<>());
        for (int i = 0; i < list.size(); i++) {
            if (i >= size * (page - 1) && i < size * page) {
                tlcarPageVo.getList().add(list.get(i));
            }
        }
        return tlcarPageVo;
    }


    @Override
    public List<TreeEntity> getCarTree(JSONObject params) {
        String carcategory = params == null ? "" : params.getString("carcategory");
        String carcategoryitem = params == null ? "" : params.getString("carcategoryitem");
        String status = params == null ? "" : params.getString("status");
        String depid = params == null ? "" : params.getString("depid");

        Map map = new HashMap();
        map.put("carcategory", carcategory);
        map.put("carcategoryitem", carcategoryitem);
        map.put("status", status);
        map.put("depid",depid);
        List<TreeEntity> treeList = sysDepartMapper.getTreeList();
        List<TreeEntity> carTree = tlCarMapper.getCarTree(map);
        treeList.addAll(carTree);
        List<TreeEntity> trees = TreeUtil.RecursiveAddress(treeList);
        return trees;
    }

    @Override
    public List<TreeEntity> getCarTree2(JSONObject params) {
        String carcategory = params == null ? "" : params.getString("carcategory");
        String carcategoryitem = params == null ? "" : params.getString("carcategoryitem");
        String status = params == null ? "" : params.getString("status");
        String depid = params == null ? "" : params.getString("depid");

        Map map = new HashMap();
        map.put("carcategory", carcategory);
        map.put("carcategoryitem", carcategoryitem);
        map.put("status", status);

        List<String> depids = departService.getChildIdsByIId(depid);
        List<TreeEntity>treeEntityList = new ArrayList<>();
        List<TreeEntity> carTree = tlCarMapper.getCarTree(map);
        for (TreeEntity treeEntity : carTree) {
            for (String s : depids) {
                if(treeEntity.getParentid().equals(s)){
                    treeEntityList.add(treeEntity);
                }
            }
        }
        List<TreeEntity> treeList = sysDepartMapper.getTreeList();

        for (TreeEntity treeEntity : treeList) {
            for (String s : depids) {
                if(treeEntity.getId().equals(s)){
                    treeEntityList.add(treeEntity);
                }
            }
        }
        treeEntityList=treeEntityList.stream().distinct().collect(toList());

        for (TreeEntity treeEntity : treeEntityList) {
            if(treeEntity.getId().equals(depid)){
                treeEntity.setParentid("");
            }
        }

//        treeEntityList.addAll(carTree);
        List<TreeEntity> trees = TreeUtil.RecursiveAddress(treeEntityList);
        return trees;
    }

//    @Override
//    public List<TreeEntity> getCarTree2() {
//        List<TreeEntity> treeList = sysDepartMapper.getTreeList();
//        List<TreeEntity> carTree = tlCarMapper.getCarTree();
//        treeList.addAll(carTree);
//        List<TreeEntity> trees = TreeUtil.RecursiveAddress(treeList);
//        return trees;
//    }

    @Override
    public int getCurrentCar(JSONObject params) throws HssException {
        QueryWrapper<TlCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlCar::getStatus, 1);
        queryWrapper.lambda().eq(TlCar::getCardeptid, params.getString("empldeptid"));
        int json = this.count(queryWrapper);
        return json;
    }

    @Override
    public int getEndOfLifeCar(JSONObject params) throws HssException {
        QueryWrapper<TlCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlCar::getStatus, 0);
        queryWrapper.lambda().eq(TlCar::getCardeptid, params.getString("empldeptid"));
        int json = this.count(queryWrapper);
        return json;
    }

    @Override
    public JSONObject getJobCategories(JSONObject params) throws HssException {
        Map<String, String> map = new HashMap();
        map.put("empldeptid", params.getString("empldeptid"));
        List<TICarVo> jobCategories = tlCarMapper.getJobCategories(map);
        JSONObject json = new JSONObject();
        json.put("data", jobCategories);
        return json;
    }

    @Override
    public JSONObject getCarType(JSONObject params) throws HssException {
        Map<String, String> map = new HashMap();
        map.put("empldeptid", params.getString("empldeptid"));
        List<TICarVo> jobCategories = tlCarMapper.getCarType(map);
        JSONObject json = new JSONObject();
        json.put("data", jobCategories);
        return json;
    }

    @Override
    public JSONObject getDriveWay(JSONObject params) throws HssException {
        Map<String, String> map = new HashMap();
        map.put("empldeptid", params.getString("empldeptid"));
        List<TICarVo> jobCategories = tlCarMapper.getDriveWay(map);
        JSONObject json = new JSONObject();
        json.put("data", jobCategories);
        return json;
    }

    @Override
    public JSONObject getOwnershipOfCar(JSONObject params) throws HssException {
        QueryWrapper<TlCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlCar::getStatus, 1);
        queryWrapper.lambda().eq(TlCar::getCardeptid, params.getString("empldeptid"));
        queryWrapper.select("carAttribution as name, count(1) as value");
        queryWrapper.lambda().groupBy(TlCar::getCarattribution);
        List<Map<String, Object>> jobCategories = this.listMaps(queryWrapper);
        JSONObject json = new JSONObject();
        json.put("data", jobCategories);
        return json;
    }

    @Override
    public JSONObject getCarManufacturers(JSONObject params) throws HssException {
        Map<String, String> map = new HashMap();
        map.put("empldeptid", params.getString("empldeptid"));
        List<TICarVo> jobCategories = tlCarMapper.getCarManufacturers(map);
        JSONObject json = new JSONObject();
        json.put("data", jobCategories);
        return json;
    }

    @Override
    public JSONObject getOldDistribution(JSONObject params) throws HssException {
        QueryWrapper<TlCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlCar::getStatus, 1);
        queryWrapper.lambda().eq(TlCar::getCardeptid, params.getString("empldeptid"));
        queryWrapper.select("floor((unix_timestamp(now())-unix_timestamp(buydate))/(365*24*3600)) as name, count(1) as value");
        queryWrapper.lambda().groupBy(TlCar::getBuydate);
        List<Map<String, Object>> jobCategories = this.listMaps(queryWrapper);
        JSONObject json = new JSONObject();
        json.put("data", jobCategories);
        return json;
    }

    @Override
    public int getCls(JSONObject params) throws HssException {
        QueryWrapper<TlCar> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(TlCar::getStatus, 1);
        queryWrapper.lambda().eq(TlCar::getCardeptid, params.getString("empldeptid"));
        int json = this.count(queryWrapper);
        return json;
    }

    @Override
    public Map<String, TlCar> getCarMap(QueryWrapper<TlCar> carQueryWrapper) {
        List<TlCar> carList = tlCarMapper.selectList(carQueryWrapper);
        Map<String, TlCar> carMap = new HashMap<>();
        if (!carList.isEmpty()) {
            carMap = GroupingByUtils.getGroupingForMapEntity(carList, TlCar::getId, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        return carMap;
    }

    @Override
    public Map<String, TlCar> getCarMapByEqpnum(QueryWrapper<TlCar> carQueryWrapper) {
        List<TlCar> carList = tlCarMapper.selectList(carQueryWrapper);
        Map<String, TlEquip> tlEquipMapByBindobjid = tlEquipService.getTlEquipMapByBindobjidMap(new QueryWrapper<>());
        carList.forEach(t->{
            TlEquip tlEquip = tlEquipMapByBindobjid.get(t.getId());
            if (Objects.nonNull(tlEquip)){
                t.setEquipcode(tlEquip.getEquipcode());
            } else {
                t.setEquipcode("");
            }
        });
        Map<String, TlCar> carMap = new HashMap<>();
        if (!carList.isEmpty()) {
            carMap = GroupingByUtils.getGroupingForMapEntity(carList, TlCar::getEquipcode, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        return carMap;
    }

    @Override
    public void excelReader(List<TlCar> tlCarList) throws ExcelReaderDataException {

        String uid = LoginUtils.getUser().getUid();
        List<SysDepart> departList = departMapper.selectList(new QueryWrapper<>());
        List<TlCarType> carTypeList = tlCarTypeMapper.selectList(new QueryWrapper<>());
        List<TlOperation> operationList = tlOperationMapper.selectList(new QueryWrapper<>());
        List<TlOperationItem> operationItemList = tlOperationItemMapper.selectList(new QueryWrapper<>());

        Map<String, TlCarType> carTypeMap = new HashMap<>();
        Map<String, TlOperation> operationMap = new HashMap<>();
        Map<String, TlOperationItem> operationItemMap = new HashMap<>();
        Map<String, SysDepart> departMap = new HashMap<>();
        if (!departList.isEmpty()) {
            Predicate<SysDepart> departNameNotNull = depart -> StringUtils.isNotEmpty(depart.getDepartName());
            departList = departList.stream().filter(departNameNotNull).collect(Collectors.toList());
            departMap = GroupingByUtils.getGroupingForMapEntity(departList, SysDepart::getDepartName, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        if (!operationList.isEmpty()) {
            Predicate<TlOperation> operationNameNotNull = operation -> StringUtils.isNotEmpty(operation.getOperationtype());
            operationList = operationList.stream().filter(operationNameNotNull).collect(Collectors.toList());
            operationMap = GroupingByUtils.getGroupingForMapEntity(operationList, TlOperation::getOperationtype, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        if (!operationItemList.isEmpty()) {
            Predicate<TlOperationItem> operationItemNameNotNull = operationItem -> StringUtils.isNotEmpty(operationItem.getItemtype());
            operationItemList = operationItemList.stream().filter(operationItemNameNotNull).collect(Collectors.toList());
            operationItemMap = GroupingByUtils.getGroupingForMapEntity(operationItemList, TlOperationItem::getItemtype, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        if (!carTypeList.isEmpty()) {
            Predicate<TlCarType> carTypeNameNotNull = car -> StringUtils.isNotEmpty(car.getTypename());
            carTypeList = carTypeList.stream().filter(carTypeNameNotNull).collect(Collectors.toList());
            carTypeMap = GroupingByUtils.getGroupingForMapEntity(carTypeList, TlCarType::getTypename, Collectors.collectingAndThen(Collectors.toList(), value -> value.get(0)));
        }
        int num = 1;
        String str = "";

        List<TlCar> tlCars = tlCarMapper.selectList(new QueryWrapper<>());
        List<String> code = tlCarList.stream().map(TlCar::getCarnumber).collect(Collectors.toList());
        if(AttributeUtils.RepeatedCheck(code) == false){
            for(Object a :AttributeUtils.RepeatedList(code)){
                str +="'第"+a+"条' 的 “车牌号:"+code.get((int)a-1)+"”  重复;##";
            }
        }

        for (TlCar car : tlCarList) {
            car.setCreatetime(new Date());
            car.setCreateby(uid);
            if (departMap.containsKey(car.getCardeptname())) {
                car.setCardeptid(departMap.get(car.getCardeptname()).getId());

            } else {
                str+="第"+num+"条的“‘所属机构’:‘"+car.getCardeptname()+"’”"+"不存在;##";
            }

            if (carTypeMap.containsKey(car.getCarTypeName())) {
                car.setCartypeid(carTypeMap.get(car.getCarTypeName()).getId());
            } else {
                str+="第"+num+"条的“‘车辆类型’:‘"+car.getCarTypeName()+"’”"+"不存在;##";
            }
            if (operationMap.containsKey(car.getCarcategoryname())) {
                car.setCarcategory(operationMap.get(car.getCarcategoryname()).getId());
            } else {
                str+="第"+num+"条的“‘作业类型’:‘"+car.getCarcategoryname()+"’”"+"不存在;##";
            }
//            if (operationItemMap.containsKey(car.getCarcategoryitemname())) {
//                car.setCarcategoryitem(operationItemMap.get(car.getCarcategoryitemname()).getId());
//            } else {
//                str+="第"+num+"条的“‘作业类型小类’:‘"+car.getCarcategoryitemname()+"’”"+"不存在;##";
//            }
            //参数判空
            if(StringUtils.isEmpty(car.getCardeptid())){
                str +="'第"+num+"条' 的 “车牌号” 不能为空;##";
            }
            if(StringUtils.isEmpty(car.getCardeptname())){
                str +="'第"+num+"条' 的 “所属机构” 不能为空;##";
            }
            if(StringUtils.isEmpty(car.getCarattribution())){
                str +="'第"+num+"条' 的 “车辆所属权” 不能为空;##";
            }
            if(StringUtils.isEmpty(car.getCarmodelname())){
                str +="'第"+num+"条' 的 “车辆型号” 不能为空;##";
            }
            if(StringUtils.isEmpty(car.getCarcategoryname())){
                str +="'第"+num+"条' 的 “作业类型” 不能为空;##";
            }

            //数据库查询判断=======================================
            int ck = 0;
            for(TlCar al: tlCars){
                if(StringUtils.isNotEmpty(al.getCarnumber()) && car.getCarnumber().equals(al.getCarnumber()) && ck == 0){
                    str += "'第"+num+"条' 档案中已存在 “车牌号:" + car.getCarnumber() + "”;";
                    ck = 1;
                }
            }
            if(ck > 0 ){
                str += "##";
            }
            //数据库查询判断结束=======================================

            num++;
        }
        if (StringUtils.isNotEmpty(str)){
            throw new ExcelReaderDataException("您导入的数据:##"+str);
        }
    }
}
